package spring.advice.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import spring.jackson.JacksonJsonUtil;
import spring.response.entity.JsonResponse;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>统一处理异常</p>
 * @author huangqiankun
 * @date 2020年8月7日下午5:15:29
 */
@Slf4j
@ControllerAdvice("指定controller的包名")
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public Object handleBindException(HttpServletRequest request, BindException e) {
        log.error("绑定参数出错, 参数: {}, 异常: {}", JacksonJsonUtil.toJson(request.getParameterMap()), e);
        if(isAjax(request)) {
            return JsonResponse.error("请求参数转换异常！");
        }else {
            return "/admin/error/404";
        }
    }

    @ExceptionHandler(Exception.class)
    public Object handleException(HttpServletRequest request, Exception e) {
        if(isAjax(request)) {
            return JsonResponse.error("xxx异常");
        }else {
            return "/admin/error/500";
        }
    }


    /**
     * 判断是否是ajax请求
     */
    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }
}
